package com.attendance.www.hr.service.impl;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Service;

import com.attendance.www.hr.beans.EmployeeBean;
import com.attendance.www.hr.beans.RoleBean;
import com.attendance.www.hr.beans.RolePageBean;
import com.attendance.www.hr.constant.AppConstant;
import com.attendance.www.hr.dao.mapper.AttachmentMapper;
import com.attendance.www.hr.dao.mapper.DepartmentMapper;
import com.attendance.www.hr.dao.mapper.EmployeeMapper;
import com.attendance.www.hr.dao.mapper.EmployeeRoleMapper;
import com.attendance.www.hr.dao.mapper.RoleDepartmentMapper;
import com.attendance.www.hr.dao.mapper.RoleExtMapper;
import com.attendance.www.hr.dao.mapper.RoleMapper;
import com.attendance.www.hr.entitys.Department;
import com.attendance.www.hr.entitys.DepartmentExample;
import com.attendance.www.hr.entitys.Employee;
import com.attendance.www.hr.entitys.EmployeeRole;
import com.attendance.www.hr.entitys.EmployeeRoleExample;
import com.attendance.www.hr.entitys.Role;
import com.attendance.www.hr.entitys.RoleDepartment;
import com.attendance.www.hr.entitys.RoleDepartmentExample;
import com.attendance.www.hr.entitys.RoleExample;
import com.attendance.www.hr.exception.ResultFaultException;
import com.attendance.www.hr.service.IRoleService;

@Service
public class RoleServiceImpl implements IRoleService {
	
	@Resource
	private RoleMapper roleDao;
	@Resource
	private RoleExtMapper roleExtDao;
	@Resource
	private RoleDepartmentMapper roleDepartmentKeyDao;
	@Resource
	private EmployeeRoleMapper employeeRoleDao;
	@Resource
	private DepartmentMapper departmentDao;
	@Resource
	private EmployeeMapper employeeDao;
	@Resource
	private AttachmentMapper attachmentDao;

	/**
	 * 新增岗位
	 */
	@Override
	public boolean saveRole(RoleBean roleBean) {
		Role role=new Role();
		role.setParentId(roleBean.getParentId());
		//RoleCode重复验证
		String roleCode=roleBean.getRoleCode();
		RoleExample roleExample=new RoleExample();
		roleExample.createCriteria()
		.andIsDisabledEqualTo(0)
		.andRoleCodeEqualTo(roleCode);
		List<Role> list=roleDao.selectByExample(roleExample);
		if (list.size()>0) {
			throw new ResultFaultException("6_00002");
		}

		role.setRoleCode(roleCode);
		role.setRoleName(roleBean.getRoleName());
		role.setDescription(roleBean.getDescription());
		role.setFromDate(roleBean.getFromDate());//生效时间，当前，改为前台传值
		int record=roleDao.insertSelective(role);
		if (record<=0) {
			return false;
		}
		String rolePath = null;
		if (roleBean.getParentId()!=null) {
			//取父级岗位
			Role rolePare =roleDao.selectByPrimaryKey(roleBean.getParentId());
			//设置rolePath
			rolePath = rolePare.getRolePath();
			rolePath = rolePath + role.getRoleId().toString() + "-";
		} else{
			rolePath = "-" + role.getRoleId().toString() + "-";
		}
		role.setRolePath(rolePath);
		roleDao.updateByPrimaryKeySelective(role);
		
		//保存岗位部门关系
		RoleDepartment roleDepartment=new RoleDepartment();
		roleDepartment.setRoleId(role.getRoleId());
		roleDepartment.setDepartmentId(roleBean.getDepartmentId());
		roleDepartment.setFromDate(roleBean.getFromDate());
		record=roleDepartmentKeyDao.insertSelective(roleDepartment);
		if(record<=0){
			return false;
		}
		return true;
	}

	/**
	 * 逻辑删除岗位
	 */
	@Override
	public boolean deleteRole(String roleId) {
		Role role=new Role();
		role.setRoleId(Integer.parseInt(roleId));
		role.setIsDisabled(1);
		int record=roleDao.updateByPrimaryKeySelective(role);
		if(record>0){
			return true;
		}else{
			return false;
		}
	}

	/**
	 * 修改岗位信息
	 */
	@Override
	public boolean updateRole(RoleBean roleBean) {
		Integer roleId=roleBean.getRoleId();
		//验证更新时间updatetime
		Role roleDB=roleDao.selectByPrimaryKey(roleId);
		if (!roleDB.getUpdateTime().equals(roleBean.getUpdateTime())) {
			throw new ResultFaultException("0_00011");
		}
		
		//RoleCode重复验证
		String roleCode=roleBean.getRoleCode();
		RoleExample roleExample=new RoleExample();
		roleExample.createCriteria().andRoleCodeEqualTo(roleCode).andRoleIdNotEqualTo(roleId).andIsDisabledEqualTo(0);
		List<Role> list=roleDao.selectByExample(roleExample);
		if (list.size()>0) {
			throw new ResultFaultException("6_00002");
		}
		
		String rolePath = null;
		//自己的岗位
		Role curRole=roleDao.selectByPrimaryKey(roleId);
		if (roleBean.getParentId()!=null) {
			//取父级岗位
			Role rolePare =roleDao.selectByPrimaryKey(roleBean.getParentId());
			//设置rolePath
			rolePath = rolePare.getRolePath();
			rolePath = rolePath + roleDB.getRoleId().toString() + "-";
			roleDB.setParentId(roleBean.getParentId());
			roleBean.setFromRolePath(curRole.getRolePath());
			roleBean.setToRolePath(rolePath);
			roleExtDao.updateRolePath(roleBean);
		} else{
			rolePath = "-" + roleDB.getRoleId().toString() + "-";
			roleBean.setFromRolePath(curRole.getRolePath());
			roleBean.setToRolePath(rolePath);
			roleExtDao.updateRolePath(roleBean);
		}
		roleDB.setRolePath(rolePath);
		roleDB.setRoleCode(roleCode);
		roleDB.setRoleName(roleBean.getRoleName());
		roleDB.setRoleLevel(roleBean.getRoleLevel());
		roleDB.setDescription(roleBean.getDescription());
		roleDB.setIsDisabled(0);
		roleDB.setUpdateTime(new Date());
		int record=roleDao.updateByPrimaryKey(roleDB);
		if (record<=0) {
			return false;
		}
		//先删除(其实双主键也可update，但有可能数据库中该主键为空，导致update失败)
		RoleDepartmentExample example=new RoleDepartmentExample();
		example.createCriteria().andRoleIdEqualTo(roleId);
		roleDepartmentKeyDao.deleteByExample(example);
		if (roleBean.getDepartmentId()!=null) {
			//再添加
			RoleDepartment roleDepartment=new RoleDepartment();
			roleDepartment.setDepartmentId(roleBean.getDepartmentId());
			roleDepartment.setRoleId(roleId);
			roleDepartment.setFromDate(roleBean.getFromDate());
			record=roleDepartmentKeyDao.insertSelective(roleDepartment);
			if (record<=0) {
				return false;
			}
		}
		return true;
	}

	/**
	 * 查询岗位
	 */
	@Override
	public RolePageBean getRoleList(RoleBean roleBean, Integer startNum, Integer pageCount) {
		RolePageBean rolePageBean=new RolePageBean();
		List<RoleBean> roleBeanList=roleExtDao.getRoleList(roleBean, startNum, pageCount);
		//循环查询所属岗位分配人员
		for(int i=0;i<roleBeanList.size();i++){
			EmployeeRoleExample employeeRoleExample=new EmployeeRoleExample();
			employeeRoleExample.createCriteria()
			.andRoleIdEqualTo(roleBeanList.get(i).getRoleId());
			List<EmployeeRole> employeeRoleList=employeeRoleDao.selectByExample(employeeRoleExample);
			List<EmployeeBean> employeeBeanList=new ArrayList<EmployeeBean>();
			for(int j=0;j<employeeRoleList.size();j++){
				Employee employee=employeeDao.selectByPrimaryKey(employeeRoleList.get(j).getEmployeeId());
				if(employee!=null){
					EmployeeBean employeeBean=new EmployeeBean();
					employeeBean.setEmployeeNo(employee.getEmployeeNo());
					employeeBean.setChineseName(employee.getChineseName());
					employeeBeanList.add(employeeBean);
				}
			}
			roleBeanList.get(i).setEmployeeBeanList(employeeBeanList);
		}
		rolePageBean.setRoleBeanList(roleBeanList);
		int pageTotal=roleExtDao.count(roleBean);
		rolePageBean.setPageTotal(pageTotal);
		return rolePageBean;
	}

	/**
	 * 查询某人的岗位集合
	 */
	@Override
	public List<RoleBean> getRoleListByEmployeeId(Integer employeeId) {
		EmployeeRoleExample employeeRoleExample=new EmployeeRoleExample();
		employeeRoleExample.createCriteria().andEmployeeIdEqualTo(employeeId);
		employeeRoleExample.setOrderByClause("is_role desc");
		//查出人员岗位关系集合
		List<EmployeeRole> employeeRoleList=employeeRoleDao.selectByExample(employeeRoleExample);
		
		List<RoleBean> roleBeanList=new ArrayList<>();
		//查询岗位信息by Id
		for (EmployeeRole employeeRole : employeeRoleList) {
			
			Role role=roleDao.selectByPrimaryKey(employeeRole.getRoleId());
			//增加部门名称
			RoleDepartmentExample roleDepartmentExample=new RoleDepartmentExample();
			roleDepartmentExample.createCriteria().andRoleIdEqualTo(role.getRoleId());
			List<RoleDepartment> rdList=roleDepartmentKeyDao.selectByExample(roleDepartmentExample);
			Department department=null;
			if (rdList.size()>0) {
				department=departmentDao.selectByPrimaryKey(rdList.get(0).getDepartmentId());
			}
			if (role.getIsDisabled()!=1) {
				//导入岗位bean
				RoleBean roleBean=new RoleBean();
				roleBean.setDescription(role.getDescription());
				roleBean.setParentId(role.getParentId());
				roleBean.setRoleCode(role.getRoleCode());
				roleBean.setRoleId(role.getRoleId());
				roleBean.setRoleLevel(role.getRoleLevel());
				roleBean.setRoleName(role.getRoleName());
				roleBean.setIsRole(employeeRole.getIsRole());
				if (department!=null) {
					roleBean.setDepartmentName(department.getDepartmentName());
					roleBean.setDepartmentCode(department.getDepartmentCode());
				}
				roleBeanList.add(roleBean);
			}
		}
		return roleBeanList;
	}

	/**
	 * 删除岗位验证，没有被分配员工可以删
	 */
	@Override
	public boolean getVerifyDelete(String roleId) {
		EmployeeRoleExample example=new EmployeeRoleExample();
		example.createCriteria().andRoleIdEqualTo(Integer.parseInt(roleId));
		List<EmployeeRole> list=employeeRoleDao.selectByExample(example);
		if (list.size()>0) {
			return true;
		}
		return false;
	}
	/**
	 * 删除岗位验证，没有被分配员工可以删
	 */
	@Override
	public List<RoleDepartment> getDepartmentRoidByRoidId(Integer departmentId) {
		RoleDepartmentExample example=new RoleDepartmentExample();
		example.createCriteria().andDepartmentIdEqualTo(departmentId);
		List<RoleDepartment> list=roleDepartmentKeyDao.selectByExample(example);
		return list;
	}

	/**
	 * 岗位信息导出
	 */
	@Override
	public String getRoleExport() {
		
		long time = System.currentTimeMillis();
		String readUrl = AppConstant.TEMPLATEFILEREPOSITORY + "/岗位信息导出模板.xlsx";
		String fileurl = AppConstant.REPORTFILEREPOSITORY + "/岗位信息导出模板" + time + ".xlsx";
		String url = AppConstant.REPORT_RESOURCE + "/岗位信息导出模板" + time + ".xlsx";
		File file = new File(readUrl);
		if (!file.exists()) {
			try {
				file.createNewFile();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

		InputStream inputStream = null;
		Workbook wb = null;
		try {
			inputStream = new FileInputStream(readUrl);
			if (readUrl.matches("^.+\\.(?i)(xls)$")) {
				wb = new HSSFWorkbook(inputStream);
			} else if (readUrl.matches("^.+\\.(?i)(xlsx)$")) {
				wb = new XSSFWorkbook(inputStream);
			} else {
				if (inputStream != null) {
					inputStream.close();
				}
				throw new ResultFaultException("8_00001");
			}
		} catch (Exception e) {
			return null;
		}

		XSSFCellStyle ztStyle = (XSSFCellStyle) wb.createCellStyle();
		Sheet sheet = wb.getSheetAt(0);
		
		//查询岗位表
		RoleExample roleExample = new RoleExample();
		com.attendance.www.hr.entitys.RoleExample.Criteria roleCriteria = roleExample.createCriteria();
		roleCriteria.andIsDisabledEqualTo(0);
		List<Role> roleList = roleDao.selectByExample(roleExample);
		HashMap<Integer,Role> roleMap = new HashMap<Integer,Role>();
		for (int i = 0; i < roleList.size(); i++) {
			roleMap.put(roleList.get(i).getRoleId(), roleList.get(i));
		}
		
		//查询岗位部门关系表
		List<RoleDepartment> rdList = roleDepartmentKeyDao.selectByExample(new RoleDepartmentExample());
		HashMap<Integer,RoleDepartment> rdMap = new HashMap<Integer,RoleDepartment>();
		for (int i = 0; i < rdList.size(); i++) {
			rdMap.put(rdList.get(i).getRoleId(),rdList.get(i));
		}
	
		//查询部门表
		DepartmentExample departmentExample = new DepartmentExample();
		com.attendance.www.hr.entitys.DepartmentExample.Criteria departmentCriteria = departmentExample.createCriteria();
		departmentCriteria.andIsDisableEqualTo(0);
		List<Department> departmentList = departmentDao.selectByExample(departmentExample);
		HashMap<Integer,Department> departmentMap = new HashMap<Integer,Department>();
		for (int i = 0; i < departmentList.size(); i++) {
			departmentMap.put(departmentList.get(i).getDepartmentId(),departmentList.get(i));
		}
		
		for (int i = 0; i < roleList.size(); i++) {
			int columns=0;
			//获取表信息
			Role role = roleList.get(i);
			//获取行
			Row row = sheet.createRow(i + 1);
			
			//获取上级岗位编码名称
			Role parentRole=roleMap.get(role.getParentId());
					
			//获取所属部门编码和名称
			RoleDepartment roleDepartment = rdMap.get(role.getRoleId());
			Department department = departmentMap.get(roleDepartment.getDepartmentId());
			//岗位编码
			this.setUpCellValue(role.getRoleCode(), columns, row, ztStyle);
			columns++;
			
			//岗位名称
			this.setUpCellValue(role.getRoleName(), columns, row, ztStyle);
			columns++;
			
			//上级岗位编码
			if(parentRole!=null) {
				this.setUpCellValue(parentRole.getRoleCode(), columns, row, ztStyle);
			}
			columns++;
			
			//上级岗位名称
			if(parentRole!=null) {
				this.setUpCellValue(parentRole.getRoleName(), columns, row, ztStyle);
			}
			columns++;
			
			//所属部门编码	
			if(department!=null) {
				this.setUpCellValue(department.getDepartmentCode(), columns, row, ztStyle);
			}
			columns++;
			
			//所属部门名称
			if(department!=null){
				this.setUpCellValue(department.getDepartmentName(), columns, row, ztStyle);
			}
			columns++;
			
			//岗位描述
			this.setUpCellValue(role.getDescription(), columns, row, ztStyle);
			columns++;
		}
		
		try {
			FileOutputStream outStream = new FileOutputStream(fileurl);
			wb.write(outStream);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return url;
	}
	
	/**
	 * 设置单元格内容
	 * 
	 * @param value
	 * @param column
	 * @param row
	 * @param cell
	 * @param ztStyle
	 */
	private void setUpCellValue(Object value, Integer columns, Row row, XSSFCellStyle ztStyle) {
		Cell cell = row.createCell(columns);
		cell.setCellStyle(ztStyle);
		if (value != null && value != "") {
			if (value.getClass() == BigDecimal.class) {
				cell.setCellValue(new BigDecimal(value.toString()).doubleValue());
			} else {
				cell.setCellValue(value.toString());
			}
		}
	}
}
